<!-- src/components/Cart.vue -->
<script setup>
import { useCartStore } from '../stores/cartStore'
import { ElButton, ElInputNumber, ElEmpty, ElMessageBox, ElInput } from 'element-plus'
import { ref, onMounted } from 'vue'
import { createOrder } from '../api/order'
import { getUserId } from '../stores/userStore'
import { format } from 'date-fns'
import { useRouter } from 'vue-router'

const router = useRouter()
const cartStore = useCartStore()
const shippingAddress = ref('')  // 新增收货地址响应式变量

// 在组件挂载时初始化购物车
onMounted(() => {
  cartStore.initializeCart()
})

const updateQuantity = (productId, quantity) => {
  if (quantity < 1) return
  cartStore.updateCartItemQuantity(productId, quantity)
}

const removeItem = (productId) => {
  cartStore.removeFromCart(productId)
}

const checkout = async () => {
  // 验证收货地址
  if (!shippingAddress.value.trim()) {
    ElMessageBox.alert('请填写收货地址', '提示', {
      confirmButtonText: '确定',
    })
    return
  }

  // 获取用户ID
  const userId = getUserId();
  if (!userId) {
    ElMessageBox.alert('请先登录', '提示', {
      confirmButtonText: '确定',
    })
    return;
  }

  // 构建订单数据
  const orderData = {
    order: {
      userid: userId,
      totalprice: cartStore.totalPrice,
      status: '未支付',
      shipping_address: shippingAddress.value, // 使用用户输入的地址
      createtime: format(new Date(), 'yyyy-MM-dd HH:mm:ss')
    },
    orderProducts: cartStore.items.map(item => ({
      productid: item.productid,
      orderprice: item.price,
      quantity: item.quantity
    }))
  };

  try {
    const response = await createOrder(orderData);
    if (response.data.code === 1) {
      const orderid = response.data.data;
      ElMessageBox.alert(`订单创建成功`, {
        confirmButtonText: '确定',
      }).then(() => {
        cartStore.clearCart();
        shippingAddress.value = '' // 清空地址输入
        cartStore.pay(orderid);
      })
    } else {
      ElMessageBox.alert(`订单创建失败: ${response.data.msg}`, '结算失败', {
        confirmButtonText: '确定',
      })
    }
  } catch (error) {
    console.error('Error creating order:', error);
    ElMessageBox.alert('订单创建失败，请稍后再试', '结算失败', {
      confirmButtonText: '确定',
    })
  }
}
</script>

<template>
  <div class="cart-container">
    <div v-if="cartStore.items.length === 0" class="empty-cart">
      <el-empty description="购物车是空的" />
    </div>

    <div v-else class="cart-content">
      <div class="cart-items">
        <div v-for="item in cartStore.items" :key="item.productid" class="cart-item">
          <img :src="item.productimg" :alt="item.title" class="product-image" />
          <div class="item-info">
            <el-input-number v-model="item.quantity" :min="1" :max="99"
              @change="(value) => updateQuantity(item.productid, value)" />
            <h3>{{ item.title }}</h3>
            <p class="price">¥{{ item.price }}</p>
            <p class="description">{{ item.description }}</p>
          </div>
          <div class="item-actions">
            <el-button type="danger" size="small" @click="removeItem(item.productid)">
              删除
            </el-button>
          </div>
        </div>
      </div>

      <!-- 新增地址输入区域 -->
      <div class="address-section">
        <el-input v-model="shippingAddress" placeholder="请输入收货地址" clearable class="address-input">
          <template #prepend>
            <span class="address-label">收货地址：</span>
          </template>
        </el-input>
      </div>

      <div class="cart-footer">
        <div class="total">
          总计: <span class="total-price">¥{{ cartStore.totalPrice }}</span>
        </div>
        <el-button type="danger" size="large" @click="checkout">
          结算 ({{ cartStore.totalItems }}件)
        </el-button>
      </div>
    </div>
  </div>
</template>

<style scoped>
.cart-container {
  padding: 20px;
  min-height: calc(100vh - 110px);
  background-color: #f5f5f5;
  display: flex;
  flex-direction: column;
}

.cart-content {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.cart-items {
  flex: 1;
  margin-bottom: 80px;
  /* 为底部留出空间 */
}

.cart-item {
  display: flex;
  align-items: center;
  padding: 20px;
  margin-bottom: 15px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.product-image {
  width: 120px;
  height: 120px;
  object-fit: cover;
  margin-right: 20px;
  border-radius: 4px;
}

.item-info {
  flex: 1;
  margin-right: 20px;
}

.item-info h3 {
  margin: 10px 0;
  color: #333;
}

.price {
  color: #ff6b6b;
  font-size: 18px;
  font-weight: bold;
  margin: 5px 0;
}

.description {
  color: #666;
  font-size: 14px;
  margin: 5px 0;
}

.item-actions {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.address-section {
  padding: 15px;
  background: white;
  position: fixed;
  bottom: 120px;
  left: 0;
  right: 0;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
}

.address-input {
  max-width: 600px;
  margin: 0 auto;
}

.address-label {
  color: #666;
  font-weight: bold;
}

.cart-footer {
  position: fixed;
  bottom: 55px;
  left: 0;
  right: 0;
  padding: 15px;
  background: white;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
}

.total {
  font-size: 16px;
  margin-left: 20px;
}

.total-price {
  color: #ff6b6b;
  font-size: 20px;
  font-weight: bold;
  margin-left: 5px;
}
</style>